package com.example.test_system.api;

import com.example.test_system.service.UserService;
import com.example.test_system.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody com.example.test_system.model.User user){
        boolean login_success = userService.login(user);

        Map<String, String> userMap = new HashMap<>();
        userMap.put("username", user.getUsername());
        String token = JWTUtils.getToken(userMap);

        Map<String, Object> res = new HashMap<>();
        res.put("state", login_success);
        res.put("token", token);

        return res;
    }

    @RequestMapping("/register")
    public Map<String, Object> register(@RequestBody com.example.test_system.model.User user){
        boolean registered = userService.register(user);

        Map<String, Object> res = new HashMap<>();
        res.put("state", registered);

        return res;
    }
}
